package com.example.mq.demo.producer;

import com.example.mq.demo.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;

@Slf4j
@Component
public class MessageProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    @Qualifier("customTxRocketMQTemplate")  // 指定 Bean 名称
    private RocketMQTemplate customTxRocketMQTemplate;


    // 发送普通消息
    public void sendMessage(Message message, String topic) {
        rocketMQTemplate.convertAndSend(topic, message);
        log.info("发送消息成功：{}", message);
    }

    // 发送同步消息
    public void sendSyncMessage(Message message, String topic) {
        rocketMQTemplate.syncSend(topic, message);
        log.info("发送同步消息成功：{}", message);
    }

    // 发送异步消息
    public void sendAsyncMessage(Message message, String topic) {
        rocketMQTemplate.asyncSend(topic, MessageBuilder.withPayload(message).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步消息发送成功：{}", sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("异步消息发送失败：", throwable);
            }
        });
    }

    // 发送延迟消息
    public void sendDelayMessage(Message message, String topic, int delayLevel) {
        rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(message).build(), 3000, delayLevel);
        log.info("发送延迟消息成功：{}", message);
    }

    // 发送顺序消息
    public void sendOrderedMessage(Message message, String topic, String shardingKey) {
        rocketMQTemplate.syncSendOrderly(topic, message, shardingKey);
        log.info("发送顺序消息成功：{}", message);
    }

    // 发送事务消息
    public void sendTransactionMessage(Message message, String topic) {
        customTxRocketMQTemplate.sendMessageInTransaction(topic, MessageBuilder.withPayload(message).build(), null);
        log.info("发送事务消息成功：{}", message);
    }
}